package com.lagou.ipersistence.transaction.jdbc;

import com.lagou.ipersistence.session.TransactionIsolationLevel;
import com.lagou.ipersistence.transaction.Transaction;
import com.lagou.ipersistence.transaction.TransactionException;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author Yan Jiahong
 * Created on 2020/11/22
 */
public class JdbcTransaction implements Transaction {
    protected Connection connection;
    protected DataSource dataSource;
    protected TransactionIsolationLevel level;
    protected boolean autoCommit;
    
    public JdbcTransaction(DataSource dataSource, TransactionIsolationLevel level, boolean autoCommit) {
        this.dataSource = dataSource;
        this.level = level;
        this.autoCommit = autoCommit;
    }
    
    public JdbcTransaction(Connection connection) {
        this.connection = connection;
    }
    
    @Override
    public Connection getConnection() throws SQLException {
        if (connection == null) {
            openConnection();
        }
        return connection;
    }
    
    private void openConnection() throws SQLException {
        connection = dataSource.getConnection();
        if (level != null) {
            connection.setTransactionIsolation(level.getLevel());
        }
        setDesiredAutoCommit(autoCommit);
    }
    
    private void setDesiredAutoCommit(boolean desiredAutoCommit) {
        try {
            if (connection.getAutoCommit() != desiredAutoCommit) {
                connection.setAutoCommit(desiredAutoCommit);
            }
        } catch (SQLException e) {
            throw new TransactionException("设置自动提交时候出错, 你的驱动器可能不支持自动提交设置" + e, e);
        }
    }
    
    @Override
    public void commit() throws SQLException {
        connection.commit();
    }
    
    @Override
    public void rollback() throws SQLException {
    
    }
    
    @Override
    public void close() throws SQLException {
        connection.close();
    }
    
    @Override
    public Integer getTimeout() throws SQLException {
        return null;
    }
}
